package com.karry.service.impl;

import cn.hutool.core.util.StrUtil;
import com.karry.mapper.BlogMapper;
import com.karry.mapper.RecordMapper;
import com.karry.mapper.TypeMapper;
import com.karry.mapper.UserMapper;
import com.karry.pojo.Blog;
import com.karry.pojo.SensitiveWord;
import com.karry.pojo.Type;
import com.karry.pojo.User;
import com.karry.service.BlogService;
import com.karry.util.Page;
import com.karry.util.SqlSessionFactoryUtils;
import com.karry.vo.BlogVo;
import com.karry.vo.ResultInfo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BlogServiceImpl implements BlogService {

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public ResultInfo<List<Blog>> searchBlogListByUserID(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        ResultInfo<List<Blog>> resultInfo = new ResultInfo<>();

        List<Blog> blogs = mapper.searchBlogListByUserID(id);

        resultInfo.setResult(blogs);

        sqlSession.close();
        //视查询结果返回指定值
        if (blogs != null){
            resultInfo.setCode(1);
        }else {
            resultInfo.setCode(0);
        }

        return resultInfo;

    }

    @Override
    public ResultInfo<Map<String, Object>> searchBlogCountByMonth(int id) {
        ResultInfo<Map<String, Object>> resultInfo = new ResultInfo<>();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        // 通过月份分类查询云记数量
        List<BlogVo> blogVos = mapper.findBlogCountByDate(id);

        // 判断集合是否存在
        if (blogVos != null && blogVos.size() > 0) {
            // 得到月份
            List<String> monthList = new ArrayList<>();
            // 得到云记集合
            List<Integer> noteCountList = new ArrayList<>();

            // 遍历月份分组集合
            for (BlogVo blog: blogVos) {
                monthList.add(blog.getGroupName());
                noteCountList.add((int)blog.getGroupCount());
            }

            // 准备Map对象，封装对应的月份与云记数量
            Map<String, Object> map = new HashMap<>();
            map.put("monthArray", monthList);
            map.put("dataArray", noteCountList);

            // 将map对象设置到ResultInfo对象中
            resultInfo.setCode(1);
            resultInfo.setResult(map);
        }
        return resultInfo;
    }

    @Override
    public ResultInfo<Map<String, Object>> searchBlogCountByUser() {
        ResultInfo<Map<String, Object>> resultInfo = new ResultInfo<>();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        // 通过月份分类查询云记数量
        List<BlogVo> blogVos = mapper.findBlogCountByUser();

        // 判断集合是否存在
        if (blogVos != null && blogVos.size() > 0) {
            // 得到用户
            List<String> monthList = new ArrayList<>();
            // 得到云记集合
            List<Integer> noteCountList = new ArrayList<>();

            // 遍历用户分组集合
            for (BlogVo blog: blogVos) {
                monthList.add(blog.getGroupName());
                noteCountList.add((int)blog.getGroupCount());
            }

            // 准备Map对象，封装对应的用户与云记数量
            Map<String, Object> map = new HashMap<>();
            map.put("userArray", monthList);
            map.put("dataArray", noteCountList);

            // 将map对象设置到ResultInfo对象中
            resultInfo.setCode(1);
            resultInfo.setResult(map);
        }
        return resultInfo;
    }

    @Override
    public Blog searchBlogById(int blogId) {

        if (blogId == -1){
            return null;
        }
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = mapper.searchBlogById(blogId);
        sqlSession.close();
        return blog;
    }

    @Override
    public Page<Blog> findBlogListByPage(String pageNumStr, String pageSizeStr, Integer id, String title, String date, String typeId, int r) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        // 设置分页参数的默认值
        Integer pageNum = 1; // 默认当前页是第一页
        Integer pageSize = 10; // 默认每页显示10条数据
        // 1. 参数的非空校验 （如果参数不为空，则设置参数）
        if (!StrUtil.isBlank(pageNumStr)) {
            // 设置当前页
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (!StrUtil.isBlank(pageSizeStr)) {
            // 设置每页显示的数量
            pageSize = Integer.parseInt(pageSizeStr);
        }

        if (title != null && title.length() > 0){
            //实现模糊查询
            title = "%" +title + "%";
        }

        // 2. 查询当前登录用户的云记数量，返回总记录数 （long类型）
        long count = mapper.findBlogCount(id, title, date, typeId, r);
        // 3. 判断总记录数是否大于0
        if (count < 1) {
            sqlSession.close();
            return null;
        }

        System.out.println("title:" + title);

        // 4. 如果总记录数大于0，调用Page类的带参构造，得到其他分页参数的值，返回Page对象
        Page<Blog> page = new Page<>(pageNum, pageSize, count);
        // 得到数据库中分页查询的开始下标
        Integer index = (pageNum -1) * pageSize;
        // 5. 查询当前登录用户下当前页的数据列表，返回note集合
        List<Blog> blogList = mapper.findBlogListByPage(id, index, pageSize, title, date, typeId, r);
        System.out.println("blogList:" + blogList);
        System.out.println(blogList.size());
        // 6. 将note集合设置到page对象中
        page.setDataList(blogList);
        // 7. 返回Page对象
        sqlSession.close();
        return page;
    }

    @Override
    public List<BlogVo> findNoteCountByDate(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        List<BlogVo> blogVos = mapper.findBlogCountByDate(id);
        sqlSession.close();
        return blogVos;
    }


    @Override
    public List<BlogVo> findNoteCountByType(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        List<BlogVo> blogVos = mapper.findBlogCountByType(id);
        sqlSession.close();
        return blogVos;
    }

    @Override
    public ResultInfo<Blog> addOrUpdate(String typeId, String title, String content, String blogId, String lon, String lat, int isOpen, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        RecordMapper record = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<Blog> resultInfo = new ResultInfo<>();

        // 1. 参数的非空判断
        if (StrUtil.isBlank(typeId)) {
            resultInfo.setCode(0);
            resultInfo.setMsg("请选择云记类型！");
            sqlSession.close();
            return  resultInfo;
        }
        if (StrUtil.isBlank(title)) {
            resultInfo.setCode(0);
            resultInfo.setMsg("云记标题不能为空！");
            sqlSession.close();
            return  resultInfo;
        }
        if (StrUtil.isBlank(content)) {
            resultInfo.setCode(0);
            resultInfo.setMsg("云记内容不能为空！");
            sqlSession.close();
            return  resultInfo;
        }

        if (title.length() > 30){
            resultInfo.setCode(0);
            resultInfo.setMsg("云记标题不能超过30位！");
            sqlSession.close();
            return  resultInfo;
        }

        // 设置经纬度的默认，默认设置为北京  116.404, 39.915
        if (lon == null || lat == null || lon.length() <= 0 || lat.length() <= 0) {
            lon = "116.404";
            lat = "39.915";
        }

        Integer bId = null;
        int tId = Integer.parseInt(typeId);
        float lonN = Float.parseFloat(lon), latN = Float.parseFloat(lat);

        if (blogId != null && blogId.length() >0) {
            bId = Integer.parseInt(blogId);
        }

        //获取用户
        User user = (User) request.getSession().getAttribute("user");
        //获取类型名
        TypeMapper mapper2 = sqlSession.getMapper(TypeMapper.class);
        Type type = mapper2.getTypeById(tId);

        int row = 0;
        //判断该文是否存在
        if (mapper.searchBlogById(bId) == null){
            //不存在则创建
            System.out.println(tId + " " + type.getName()+ " " +  title+ " " +  content+ " " +  user.getId()+ " " +  user.getName()+ " " +  lonN+ " " +  latN);

            //创建blog对象
            Blog blog = new Blog();
            blog.setContent(content);
            blog.setIsOpen(isOpen);
            blog.setLan(latN);
            blog.setLon(lonN);
            blog.setTitle(title);
            blog.setTypeID(tId);
            blog.setTypeName(type.getName());
            blog.setUserID(user.getId());
            blog.setUserName(user.getName());
            row = mapper.insertBlog(blog);
            System.out.println("插入博客修改行数：" + row +"  新增博客id:" + blog.getId());
            //row = mapper.insertBlog(tId, type.getName(), title, content, user.getId(), user.getName(), lonN, latN, isOpen);
            //获得主键值，便于插入记录
            if (row > 0){
                //记录
                record.insertRecord("添加博客", user.getId(), blog.getId(), blog.getTitle(), blog.getTypeName());
            }
        }else {
            //存在则修改
            row = mapper.updateBlog(bId, tId, type.getName(), title, content, user.getId(), user.getName(), lonN, latN, isOpen);
            if (row > 0){
                //记录
                record.insertRecord("修改博客", user.getId(), bId, title, type.getName());
            }
        }

        // 4. 判断受影响的行数
        if (row > 0) {
            resultInfo.setCode(1);
        } else {
            resultInfo.setCode(0);
            resultInfo.setMsg("更新失败！");
        }
        sqlSession.close();
        return resultInfo;
    }

    @Override
    public Integer deleteBlog(String blogId, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        RecordMapper record = sqlSession.getMapper(RecordMapper.class);

        int id = Integer.parseInt(blogId);
        int i = mapper.deleteBlog(id);
        if (i > 0){
            User user = (User) request.getSession().getAttribute("user");
            //记录
            record.insertRecord("删除博客", user.getId(), id, "#", "#");
        }
        sqlSession.close();
        return i > 0 ? 1 : 0;
    }

    @Override
    public boolean sensitiveCheck(String title, String type, String content, String name) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        /**  获取全部违规词  **/
        ArrayList<SensitiveWord> sensitiveWords = mapper.searchAllWord();

            for (SensitiveWord sensitiveWord : sensitiveWords) {
                String word = sensitiveWord.getWord();
                if (title.contains(word) || type.contains(word) || content.contains(word) || name.contains(word)){

                    return false;
                }
            }
        sqlSession.close();
        return true;
    }

    @Override
    public Page<Blog> getAllBlogListByPage(int pageNum) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        //查询用户总数
        int count = mapper.getBlogCount();

        ArrayList<Blog> blogs = mapper.getBlogListByPage((pageNum - 1) * 10);
        Page<Blog> page = new Page<>(pageNum, 10, count);
        page.setDataList(blogs);
        System.out.println(page);
        sqlSession.close();
        return page;
    }

    @Override
    public ResultInfo<Integer> liveBlog(int id, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        RecordMapper recordMapper = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<Integer> resultInfo = new ResultInfo<>();
        int i = mapper.liveBlog(id);
        if (i > 0){
            resultInfo.setCode(1);
            User user = (User) request.getSession().getAttribute("user");
            //根据书籍获取用户id
            Blog blog = mapper.searchBlog(id);
            recordMapper.insertRecord("恢复博客", blog.getUserID(), id , "管理员恢复该博客", "管理员ID: " + user.getId());
        }else {
            resultInfo.setCode(0);
            resultInfo.setMsg("恢复失败");
        }
        sqlSession.close();
        return resultInfo;
    }

    @Override
    public ResultInfo<Integer> closeBlog(int id, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        RecordMapper recordMapper = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<Integer> resultInfo = new ResultInfo<>();
        int i = mapper.closeBlog(id);
        if (i > 0){
            resultInfo.setCode(1);
            User user = (User) request.getSession().getAttribute("user");
            //根据书籍获取用户id
            Blog blog = mapper.searchBlog(id);
            recordMapper.insertRecord("私密博客", blog.getUserID(), id , "管理员私密该博客", "管理员ID: " + user.getId());

        }else {
            resultInfo.setCode(0);
            resultInfo.setMsg("设置私密失败");
        }
        sqlSession.close();
        return resultInfo;
    }

    @Override
    public ResultInfo<Integer> openBlog(int id, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        RecordMapper recordMapper = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<Integer> resultInfo = new ResultInfo<>();
        int i = mapper.openBlog(id);
        if (i > 0){
            resultInfo.setCode(1);
            User user = (User) request.getSession().getAttribute("user");
            //根据书籍获取用户id
            Blog blog = mapper.searchBlog(id);
            recordMapper.insertRecord("开放博客", blog.getUserID(), id , "管理员开放该博客", "管理员ID: " + user.getId());
        }else {
            resultInfo.setCode(0);
            resultInfo.setMsg("设置开放失败");
        }
        sqlSession.close();
        return resultInfo;
    }

    @Override
    public ResultInfo<Integer> deleteBlog2(int id, HttpServletRequest request) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        RecordMapper recordMapper = sqlSession.getMapper(RecordMapper.class);
        ResultInfo<Integer> resultInfo = new ResultInfo<>();
        int i = mapper.deleteBlog(id);
        if (i > 0){
            resultInfo.setCode(1);
            User user = (User) request.getSession().getAttribute("user");
            //根据书籍获取用户id
            Blog blog = mapper.searchBlog(id);
            recordMapper.insertRecord("删除博客", blog.getUserID(), id , "管理员删除该博客", "管理员ID: " + user.getId());
        }else {
            resultInfo.setCode(0);
            resultInfo.setMsg("删除失败");
        }
        sqlSession.close();
        return resultInfo;
    }

    @Override
    public int addViewCount(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        int i = mapper.addViewCount(id);
        sqlSession.close();
        return i;
    }

    @Override
    public ArrayList<Blog> getAllBlog() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        ArrayList<Blog> allBlog = mapper.getAllBlog();
        sqlSession.close();
        return allBlog;
    }
}
